import os
import time
import shutil
import zipfile


def copy_folder_files(source_path, target_path):
    # 调用shutil模块的copytree方法，将源路径下的所有内容复制到目标路径
    # 如果目标路径已经存在，会抛出FileExistsError异常
    shutil.copytree(source_path, target_path)
    # 打印复制成功的信息
    print(f"Successfully copied {source_path} to {target_path}")


def copy_file(source_file_path, target_folder_path):
    return


def release_folder_search(folder_path):
    matched_folders = []
    for item in os.listdir(folder_path):
        full_path = os.path.join(folder_path, item)
        if os.path.isdir(full_path):
            if item.startswith("build") and item.endswith("Release"):
                matched_folders.append(item)
    return folder_path + "\\" + matched_folders[0]


def mkdir(path):
    folderSuffix = "release_" + time.strftime("%Y%m%d_%H%M%S")
    folderPath = path + folderSuffix
    return folderPath

# def mkdir(path):
#     folderSuffix = "release_" + time.strftime("%Y%m%d_%H%M%S")
#     folderPath = path + folderSuffix
#     isFolder = os.path.exists(folderPath)
#
#     if not isFolder:
#         os.makedirs(folderPath)
#         print("--- new folder " + path)
#         return folderPath
#
#     else:
#         print("--- folder exists")


def zipDir(dirpath, outFullName):
    """
    压缩指定文件夹
    :param dirpath: 目标文件夹路径
    :param outFullName: 压缩文件保存路径+xxxx.zip
    :return: 无
    """
    zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
    for path, dirnames, filenames in os.walk(dirpath):
        # 去掉目标跟路径，只对目标文件夹下边的文件及文件夹进行压缩
        fpath = path.replace(dirpath, '')

        for filename in filenames:
            zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
    zip.close()


if __name__ == "__main__":
    release_folderPath = mkdir(os.getcwd() + "\\")
    print(release_folderPath)
    build_folderPath = release_folder_search(os.getcwd())
    print(build_folderPath)
    buildUiPath = build_folderPath + "\\ui\\release\\ui.exe"
    print(buildUiPath)
    chajianFolderPath = os.getcwd() + "\\bokun\\chajian"
    print(chajianFolderPath)
    copy_folder_files(chajianFolderPath, release_folderPath)
    os.popen("copy " + buildUiPath + " " + release_folderPath)
    command = "windeployqt.exe " + release_folderPath + "\\ui.exe"
    os.system(command)
    zipDir(release_folderPath, release_folderPath + ".zip")